package org.akomantoso.core.io.util;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.ComponentRef;
import org.akomantoso.core.data.MainContentElement;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.group.BlockElementsGroup;
import org.akomantoso.core.io.util.group.ContainerElementsGroup;
import org.akomantoso.core.io.util.group.HierElementsGroup;
import org.akomantoso.core.util.MapUtil;

/**
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 */
public final class MainContentElementUtil {

	private MainContentElementUtil() {
	}

	static final Map<String, Instantiator<MainContentElement>> MAP = new IdentityHashMap<String, Instantiator<MainContentElement>>();

	
	public static void read(Input in,List<MainContentElement> elements) throws IOException {
		MainContentElement element = null;
		final String localName = in.getLocalName();
		
		int eventType;
		
		while(true) {
			eventType = in.readNext();
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(element = instantiate(in.getLocalName()));
				element.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName == in.getLocalName()) {
					return;
				} 
			}
		}
	}
	
	private static MainContentElement instantiate(String element) {
		final Instantiator<MainContentElement> instatiator = MAP.get(element);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + element + "] not supported MainContentElement ?!?");
		}
		return instatiator.instantiate();
	}
	
	static {
		MapUtil.copy(HierElementsGroup.MAP, MAP);
		MapUtil.copy(BlockElementsGroup.MAP, MAP);
		MapUtil.copy(ContainerElementsGroup.MAP, MAP);
		MAP.put(ComponentRef.ELEMENT, new Instantiator<MainContentElement>() {
			public ComponentRef instantiate() {
				return new ComponentRef();
			}
		});
	}

}